(function($, com) {
	var state = app.getState();
	var uid = state.user_id;
	var getObjLen = function(obj) {
		return Object.keys(obj).length;
	}
	
	/**
	 * 获取所有聊天对象
	 */
	com.getAll = function() {
		var data = plus.storage.getItem(uid + 'chatdata');
		//console.log(data);
		if(data) {
			return JSON.parse(data);
		} else {
			return {};
		}
	};
	/**
	 * 设置数据
	 * @param {Object} data
	 */
	com.setData = function(data){
		plus.storage.setItem(uid + 'chatdata', JSON.stringify(data));
	}
	/**
	 * 获取单个聊天对象
	 */
	com.getChat = function(roomId) {
		var data = plus.storage.getItem(uid + 'persondata' + roomId);
		//console.log(data);
		if(data) {
			return JSON.parse(data);
		} else {
			return {};
		}
	};
	/**
	 * 设置单个聊天对象数据
	 * @param {Object} data
	 */
	com.setChat = function(roomId, data){
		plus.storage.setItem(uid + 'persondata' + roomId, JSON.stringify(data));
	}
	/**
	 * 设置首页缓存
	 * @param {Object} data
	 */
	com.setIndex = function(data){
		localStorage.setItem(uid + 'indexdata', JSON.stringify(data));
	};
	/**
	 * 获取首页缓存
	 */
	com.getIndex = function(){
		var data = localStorage.getItem(uid + 'indexdata');
		if(data) {
			return JSON.parse(data);
		} else {
			return {};
		}
	};
	com.HTMLDecode = function(text) {
		var temp = document.createElement("div");
		temp.innerHTML = text;
		var output = temp.innerText || temp.textContent;
		temp = null;
		return output;
	}
	var sorttime = function(a,b){
			return b['add_time'] - a['add_time'];
	};
	
	com.getList = function() {
		var data = com.getAll();
		var len = getObjLen(data);
		var top = [];
		var main = [];
		if(len < 1) {
			return main;
		}
		for(var p in data) {
			var msglist = data[p]['list'];
			for(var lastId in msglist) {}
			var show = msglist[lastId];
			show['show_time'] = app.dateStr(show['add_time']);
			if(show['f_id'] == uid) {
				show['name'] = show['t_name'];
				var fid = show['t_id'];
			}else{
				show['name'] = show['f_name'];
				var fid = show['f_id'];
			}
			
			//console.log(headerimg);
			if(show['ctype'] == 2) {
				show['name'] = show['t_name'];
				show['avatar'] = 'static/images/qun.png';
			} else {
				show['avatar'] = app.avatar(p, 'static/images/1.png');
			}
			//console.log(show['avatar']); 
			show['msgnum'] = data[p]['msgnum'];
			show['istop'] = data[p]['istop'] || 0;
			show['msg'] = app.parseMainMsg(show['t_msg'], show['r_type']);
			show['msg'] = com.HTMLDecode(show['msg']);
			show['key'] = p;
			if(show['name']) {
				if(show['istop'] > 0) {
					top.push(show);
				}else{
					main.push(show);
				}
				
			}
			
		}
		//app.arrSort(main, 'add_time');
		top.sort(sorttime);
		main.sort(sorttime);
		top.push.apply(top,main);
		/*
		main.sort(function(a,b){
			return b['istop'] - a['istop'];
		});*/
	    return top;
	}
	/**
	 * 获取所有群组
	 * @param {Object} roomId
	 */
	com.getRoomData = function(roomId) {
		var qdata = JSON.parse(localStorage.getItem('qunlist' + uid)) || [];
		var news, len = qdata.length,
			i = 0,
			has = false;
		for(; i < len; i++) {
			if(qdata[i]['room_id'] == room_id) {
				news = qdata[i];
				has = true;
				break;
			}
		}
		if(has === false) {
			return [];
		}else{
			return news;
		}
	};
	/**
	 * 获取单个聊天对象
	 */
	com.get = function(roomId) {
		var data = com.getAll();
		//console.log(roomId);
		//console.log(JSON.stringify(data));
		return data[roomId];
	}
	/**
	 * 设置单个聊天对象
	 */
	com.set = function(roomId, msgInfo) {
		var data = com.getAll();
		var id = msgInfo['id'];
		if(!data[roomId]) {
			data[roomId] = {};
		}
		if(!data[roomId]['list']) {
			data[roomId]['list'] = {};
		}
		if(msgInfo['ctype'] == 1) {
			if(msgInfo['f_id'] != uid) {
				data[roomId]['msgnum']++;
				data[roomId]['name'] = msgInfo['f_name'];
				//data[roomId]['avatar'] = msgInfo['f_header'];
			}else{
				data[roomId]['name'] = msgInfo['t_name'];
			}
			data[roomId]['avatar'] = app.avatar(roomId, 'static/images/1.png');
		}else{
			data[roomId]['msgnum']++;
			data[roomId]['name'] = msgInfo['t_name'];
			data[roomId]['avatar'] = app.avatar(roomId, 'static/images/qun.png');
		}
		
		data[roomId]['list'][id] = msgInfo;
		com.setData(data);
	}
	com.clearnum = function(roomId) {
		var data = com.getAll();
		if(data[roomId]){
			data[roomId]['msgnum'] = 0;
		}
		
		com.setData(data);
	}
	com.edit = function(roomId, id, field, val) {
		var data = com.getAll();
		data[roomId]['list'][id][field] = val;
		com.setData(data);
	}
	com.setnum = function(roomId, num){
		var data = com.getAll();
		data[roomId]['msgnum'] = num;
		com.setData(data);
	};
	com.setval = function(roomId, field, val){
		var data = com.getAll();
		data[roomId][field] = val;
		com.setData(data);
	};
	/**
	 * 删除单个聊天组
	 * @param {Object} roomId
	 */
	com.del = function(roomId) {
		var data = com.getAll();
		delete data[roomId];
		com.setData(data);
	}
	/**
	 * 删除单个聊天组的某句话
	 * @param {Object} roomId
	 */
	com.delOne = function(roomId, id) {
		var data = com.getAll();
		delete data[roomId]['list'][id];
		com.setData(data);
	}
	com.getId = function(roomId) {
		return uid + '-' + roomId + '-' + Date.parse(new Date());
	};
	com.updateList = function(rtinfo){
		var person = rtinfo['person'];
		var personlen = person.length;
		var room = rtinfo['room'];
		var roomlen = room.length;
		var data = com.getIndex();
		var cache = {};
		if(personlen > 0) {
			for(var p in person) {
				var pdata = person[p];
				var roomId = pdata['f_id'];
				if(!data[roomId]) {
					data[roomId] = {};
				}
				if(!cache[roomId]) {
					cache[roomId] = {};
				}
				data[roomId]['name'] = pdata['f_name'];
				data[roomId]['avatar'] = pdata['f_header'];
				//var msgnum = 0;
				var id = pdata['id'] ? pdata['id'] : com.getId()+parseInt(Math.random()*10000);
				cache[roomId][id] = pdata;
				if(!data[roomId]['msgnum']){
					data[roomId]['msgnum'] = 0;
				}
				data[roomId]['msgnum']++;
				
			}
		}
		if(roomlen > 0) {
			for(var p in room) {
				var pdata = room[p];
				var roomId = pdata['t_id'];
				if(!data[roomId]) {
					data[roomId] = {};
				}
				if(!cache[roomId]) {
					cache[roomId] = {};
				}
				data[roomId]['name'] = pdata['t_name'];
				data[roomId]['avatar'] = 'static/images/qun.png';
				var id = pdata['id'] ? pdata['id'] : com.getId()+parseInt(Math.random()*10000);
				cache[roomId][id] = pdata;
				if(!data[roomId]['msgnum']){
					data[roomId]['msgnum'] = 0;
				} 
				data[roomId]['msgnum']++;
				
			}
		}
		for(var roomId in data) {
			var chatdata = com.getChat(roomId);
			var listdata = data[roomId];
			var cachedata = cache[roomId];
			chatdata['name'] = listdata['name'];
			chatdata['avatar'] = listdata['avatar'];
			if(!chatdata['list']) {
				chatdata['list'] = {};
			}
			for(var id in cachedata) {
				chatdata['list'][id] = cachedata[id];
			}
			com.setChat(roomId, chatdata);
		}
		com.setIndex(data);
	};
	com._updateList = function(rtinfo){
		var person = rtinfo['person'];
		var personlen = person.length;
		var room = rtinfo['room'];
		var roomlen = room.length;
		var data = com.getAll();
		var cache = {};
		if(personlen > 0) {
			for(var p in person) {
				var pdata = person[p];
				var roomId = pdata['f_id'];
				if(!data[roomId]) {
					data[roomId] = {};
				}
				if(!data[roomId]['list']) {
					data[roomId]['list'] = {};
				}
				data[roomId]['name'] = pdata['f_name'];
				data[roomId]['avatar'] = pdata['f_header'];
				//var msgnum = 0;
				var id = pdata['id'] ? pdata['id'] : com.getId()+parseInt(Math.random()*10000);
				data[roomId]['list'][id] = pdata;
				if(!data[roomId]['msgnum']){
					data[roomId]['msgnum'] = 0;
				}
				data[roomId]['msgnum']++;
				/*
				for(var j in pdata) {
					var jdata = pdata[j];
					var id = jdata['id'] ? jdata['id'] : com.getId()+parseInt(Math.random()*10000);
					data[roomId]['list'][id] = jdata;
					msgnum++;
				}*/
			}
		}
		if(roomlen > 0) {
			for(var p in room) {
				var pdata = room[p];
				var roomId = pdata['t_id'];
				if(!data[roomId]) {
					data[roomId] = {};
				}
				if(!data[roomId]['list']) {
					data[roomId]['list'] = {};
				}
				data[roomId]['name'] = pdata['t_name'];
				data[roomId]['avatar'] = 'static/images/qun.png';
				var id = pdata['id'] ? pdata['id'] : com.getId()+parseInt(Math.random()*10000);
				data[roomId]['list'][id] = pdata;
				if(!data[roomId]['msgnum']){
					data[roomId]['msgnum'] = 0;
				} 
				data[roomId]['msgnum']++;
				
			}
		}
		com.setData(data);
	};
	//长按消息框
	function msgIndexTap(e) {
		//console.log('触发长按');
		var el = this,
			btns = [{
				title: "删除聊天",
				tags: 'del'
			}],
			msgnum = el.getAttribute('msgnum') || 0,
			istop = el.getAttribute('istop')*1 || 0,
			room_id = el.getAttribute('room_id'),
			data_id = el.getAttribute('data_id'),
			ctype = el.getAttribute('room-type');
		//console.log(datatype);
		if(msgnum > 0) {
			btns.push({
				title: '标为已读'
			});
		} else {
			btns.push({
				title: '标为未读'
			});
		}
		if(istop > 0) {
			btns.push({
				title: '取消置顶'
			});
		} else {
			btns.push({
				title: '设为置顶'
			});
		}
		plus.nativeUI.actionSheet({
			title: "操作",
			cancel: "取消",
			buttons: btns
		}, function(e) {
			//console.log("User pressed: " + e.index);
			var id = e.index;
			console.log(id);
			if(id > 0) {
				//删除
				if(id == 1) {
					com.del(room_id);
					el.parentNode && el.parentNode.removeChild(el);

				} else if(id == 2) {
					var badge = el.querySelector('.mui-badge');
					var setval = 0;
					if(msgnum && msgnum > 0) {
						if(badge) {
							badge.parentNode.removeChild(badge);
						}
					} else {
						setval = 1;
						if(!badge) {
							var badge = document.createElement("span");
							var targetprent = el.querySelector('.mui-table-cell');
							var targetimg = targetprent.querySelector('img.mui-media-object');
							badge.setAttribute('class', 'mui-badge');
							badge.innerHTML = 1;
							targetprent.insertBefore(badge, targetimg.nextSibling);
						} else {
							badge.innerHTML = 1;
						}
					}
					el.setAttribute('msgnum', setval);
					//com.edit(room_id, data_id, 'msgnum', setval);
					com.setval(room_id, 'msgnum', setval);
				} else if(id == 3) {	
					if(istop > 0) {
						setval = 0;
					} else {
						setval = 1;
					}
					//com.edit(room_id, data_id, 'istop', setval);
					com.setval(room_id, 'istop', setval);
					com.renderlist();
				}
				//弹出菜单的显示、隐藏
				mui('.mui-popover-action').popover('toggle');
				//return true;
				//li.parentNode.removeChild(li);
			} else {
				mui('.mui-popover-action').popover('toggle');
				// return true;
			}
		});
	};

	function openchatWin() {
		var titleName = this.getAttribute('title');
		var headerImg = this.querySelector('img').getAttribute('src');
		var roomId = this.getAttribute('room_id');
		var roomType = this.getAttribute('room-type');
		//location.href = 'pages/chat/chat_index.html?chatTitle=' + titleName + '&chatHeader=' + headerImg + '&roomId=' + roomId + '&roomType' + roomType; 
		mui.openWindow({
			url: '/pages/chat/chat_index.html',
			id: 'chatbox',

			show: {
				autoShow: true,
				aniShow: 'slide-in-right',
				duration: 100
			},
			extras: {
				chatTitle: titleName,
				chatHeader: headerImg,
				roomId: roomId,
				roomType: roomType
			}
		});

	}
	com.renderlist = function() {
		var chatdata = com.getList();
		document.querySelector("#main-area").innerHTML = template('main-templete', {
			"mainlist": chatdata
		});
		$('.mui-content').on('longtap', 'li', msgIndexTap);
		$('.mui-content').on('tap', 'li', openchatWin);

	}

}(mui, window.chat = {}));